package com.peas.platform.common.core.configuration;

import cn.hutool.core.collection.CollUtil;
import com.github.xiaoymin.knife4j.spring.annotations.EnableKnife4j;
import com.peas.platform.common.core.property.SwaggerProperties;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.RequestHandler;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;

import javax.annotation.Resource;
import java.util.function.Predicate;

@Configuration
@EnableKnife4j
@Slf4j
public class Knife4jConfig {

    @Resource
    private SwaggerProperties swaggerProperties;

    @Bean(value = "docket")
    public Docket docket() {
        //指定使用Swagger2规范
        Contact contact = new Contact(swaggerProperties.getName(), swaggerProperties.getUrl(), swaggerProperties.getEmail());
        Predicate<RequestHandler> selector = RequestHandlerSelectors.none();
        if (CollUtil.isNotEmpty(swaggerProperties.getBasePackage())) {
            log.debug(swaggerProperties.getBasePackage().toString());
            for (String base : swaggerProperties.getBasePackage()) {
                selector = selector.or(RequestHandlerSelectors.basePackage(base));
            }
        } else {
            selector = selector.or(RequestHandlerSelectors.withClassAnnotation(Api.class));
        }
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(new ApiInfoBuilder()
                        .title(swaggerProperties.getTitle())
                        //描述字段支持Markdown语法
                        .description(swaggerProperties.getDescription())
                        .contact(contact)
                        .version(swaggerProperties.getVersion())
                        .termsOfServiceUrl(swaggerProperties.getTermsOfService())
                        .license(swaggerProperties.getLicense())
                        .build())
                //分组名称
                // .groupName("用户服务")
                .select()
                //这里指定Controller扫描包路径
                .apis(selector)
                .paths(PathSelectors.any())
                .build();
    }

}
